//
//  ViewController.m
//  登陆认证
//
//  Created by heew on 2017/3/2.
//  Copyright © 2017年 qeegoo. All rights reserved.
//

#import "ViewController.h"
#import "SVProgressHUD.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userNamefield;
@property (weak, nonatomic) IBOutlet UITextField *pwdfield;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *logouButton;

@end

@implementation ViewController
- (IBAction)login {
    /* Configure session, choose between:
     * defaultSessionConfiguration
     * ephemeralSessionConfiguration
     * backgroundSessionConfigurationWithIdentifier:
     And set session-wide properties, such as: HTTPAdditionalHeaders,
     HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
     */
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    
    /* Create the Request:
     My API (2) (POST http://1.1.1.2/ac_portal/login.php)
     */
    
    NSURL* URL = [NSURL URLWithString:@"http://1.1.1.2/ac_portal/login.php"];
    
    NSString *userName = self.userNamefield.text;

    [[NSUserDefaults standardUserDefaults] setValue:userName forKey:@"userName"];
    NSString *pwd = self.pwdfield.text;
    [[NSUserDefaults standardUserDefaults] setValue:pwd forKey:@"pwd"];
    
    NSDictionary* URLParams = @{
                                @"opr": @"pwdLogin",
                                @"userName": userName,
                                @"pwd": pwd,
                                @"rememberPwd": @"1",
                                };
    URL = NSURLByAppendingQueryParameters(URL, URLParams);
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"POST";
    
    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_queue_t main = dispatch_get_main_queue();
        dispatch_async(main, ^{
            if (error == nil) {
                // Success
                NSLog(@"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                self.loginButton.enabled = false;
                self.loginButton.backgroundColor = [UIColor colorWithRed:214/255.0 green:214/255.0 blue:214/255.0 alpha:1];
                self.logouButton.enabled = true;
                self.logouButton.backgroundColor = [UIColor colorWithRed:255/255.0 green:187/255.0 blue:52/255.0 alpha:1];
            }
            else {
                // Failure
                NSLog(@"URL Session Task Failed: %@", [error localizedDescription]);
                [SVProgressHUD showSuccessWithStatus:@"登录失败"];
            }
            
        });
    }];
    [task resume];
    [session finishTasksAndInvalidate];
}
- (IBAction)logout {
    
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    
    /* Create the Request:
     My API (POST http://1.1.1.2/ac_portal/login.php)
     */
    
    NSURL* URL = [NSURL URLWithString:@"http://1.1.1.2/ac_portal/login.php"];
    NSDictionary* URLParams = @{
                                @"opr": @"logout",
                                };
    URL = NSURLByAppendingQueryParameters(URL, URLParams);
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"POST";
    
    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        dispatch_queue_t main = dispatch_get_main_queue();
        dispatch_async(main, ^{
            if (error == nil) {
                // Success
                NSLog(@"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
                [SVProgressHUD showSuccessWithStatus:@"退出成功"];
                self.loginButton.enabled = true;
                self.loginButton.backgroundColor = [UIColor colorWithRed:255/255.0 green:94/255.0 blue:21/255.0 alpha:1];
                self.logouButton.enabled = false;
                self.logouButton.backgroundColor = [UIColor colorWithRed:214/255.0 green:214/255.0 blue:214/255.0 alpha:1];
                
                
            }
            else {
                // Failure
                NSLog(@"URL Session Task Failed: %@", [error localizedDescription]);
                [SVProgressHUD showSuccessWithStatus:@"退出失败"];
            }
            
        });
    }];
    [task resume];
    [session finishTasksAndInvalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *userName = [[NSUserDefaults standardUserDefaults] stringForKey:@"userName"];
    NSString *pwd =  [[NSUserDefaults standardUserDefaults] stringForKey:@"pwd"];
    _userNamefield.text = userName;
    _pwdfield.text = pwd;
    self.loginButton.enabled = true;
    self.loginButton.backgroundColor = [UIColor colorWithRed:255/255.0 green:94/255.0 blue:21/255.0 alpha:1];
    self.logouButton.enabled = false;
    self.logouButton.backgroundColor = [UIColor colorWithRed:214/255.0 green:214/255.0 blue:214/255.0 alpha:1];
}
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
    NSMutableArray* parts = [NSMutableArray array];
    [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        NSString *part = [NSString stringWithFormat: @"%@=%@",
                          [key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
                          [value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
                          ];
        [parts addObject:part];
    }];
    return [parts componentsJoinedByString: @"&"];
}

/**
 Creates a new URL by adding the given query parameters.
 @param URL The input URL.
 @param queryParameters The query parameter dictionary to add.
 @return A new NSURL.
 */
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
    NSString* URLString = [NSString stringWithFormat:@"%@?%@",
                           [URL absoluteString],
                           NSStringFromQueryParameters(queryParameters)
                           ];
    return [NSURL URLWithString:URLString];
}

@end
